package com.lzm.back.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzm.back.entity.Score;
import com.lzm.back.entity.User;
import com.lzm.back.mapper.ScoreMapper;
import com.lzm.back.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ScoreService {

    @Resource
    private ScoreMapper scoreMapper;
    @Resource
    private UserMapper userMapper;

    // 新增评分
    public void addScore(Score score) {
        score.setCreateTime(LocalDateTime.now());
        scoreMapper.insert(score);
    }

    // 批量删除
    public void deleteBatch(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) return;
        scoreMapper.deleteBatch(ids);
    }

    // 更新评分
    public void updateScore(Score score) {
        score.setUpdateTime(LocalDateTime.now());
        User judge = userMapper.selectByID(score.getJudgeId());
        score.setJudgeName(judge.getUsername());
        scoreMapper.updateByPrimaryKeySelective(score);
    }

    public PageInfo<Score> selectScore(Integer id, String username, String role, String comment, Integer pageNum, Integer pageSize, Score score) {
        PageHelper.startPage(pageNum, pageSize);

        List<Score> list = scoreMapper.selectScore(id, username, role, score.getUserId());
        return new PageInfo<>(list);
    }

    public void deleteScore(Long id) {
        scoreMapper.deleteByPrimaryKey(id);
    }

    public PageInfo<Score> selectScoreGroupByEvent(Integer id, String username, String role, String comment, Integer pageNum, Integer pageSize, Score score) {
        PageHelper.startPage(pageNum, pageSize);

        List<Score> list = scoreMapper.selectScoreGroupByEvent(id, username, role, score.getUserId());
        return new PageInfo<>(list);
    }

    public Score selectMaxAndAvg(Long userId, Long eventId) {
        return scoreMapper.selectMaxAndAvg(userId, eventId);
    }

    public List<User> selectMaxScoreParticipant(Long eventId, BigDecimal score) {
        return scoreMapper.selectMaxScoreParticipant(eventId, score);
    }
}
